<template>
  <div>
    <div
      v-for="item in dataList"
      :key="item.id"
      class="flex items-center type-wrapper"
      :class="position === 'left' ? 'justify-end' : 'justify-start'"
    >
      <card-container
        class="mr-48"
        :parent-id="item.id"
        :position="item.position"
        v-if="position === 'left'"
        :isDataDemonstration="isDataDemonstration"
        :isShare="isShare"
      />
      <link-circle :ref="item.id" :data-item="item" @handleLink="handleLink" v-if="item.existNextNode && position === 'left'" />
      <component :ref="`component${item.id}`" :is="componentActive[item.type]" :data-item="item" @handleClick="handleClick" />
      <link-circle :ref="item.id" :data-item="item" @handleLink="handleLink" v-if="item.existNextNode && position === 'right'" />
      <card-container
        class="ml-48"
        :parent-id="item.id"
        :position="item.position"
        v-if="position === 'right'"
        :isDataDemonstration="isDataDemonstration"
        :isShare="isShare"
      />
    </div>
  </div>
</template>

<script>
import { mindQueryNextNodes } from '@/api/tool/gen.js'
import { createId } from '@/utils/tools-mind'
import moment from 'moment'
import LinkCircle from '@/views/mind/components/common/link-circle.vue'
import CardCategory from '@/views/mind/components/cards/card-category.vue'
import CardSale from '@/views/mind/components/cards/card-sale.vue'
import CardSaleList from '@/views/mind/components/cards/card-sale-list.vue'
import CardRectification from '@/views/mind/components/cards/card-rectification.vue'
import CardComplain from '@/views/mind/components/cards/card-complain.vue'
import CardComplainList from '@/views/mind/components/cards/card-complain-list.vue'
import CardShip from '@/views/mind/components/cards/card-ship.vue'
import CardOutStock from '@/views/mind/components/cards/card-out-stock.vue'
import CardOutStockList from '@/views/mind/components/cards/card-out-stock-list.vue'
import CardPlan from '@/views/mind/components/cards/card-plan.vue'
import CardProduction from '@/views/mind/components/cards/card-production.vue'
import CardKeyBind from '@/views/mind/components/cards/card-key-bind.vue'
import CardDeviceAbnormal from '@/views/mind/components/cards/card-device-abnormal.vue'
import CardProductionInOrder from '@/views/mind/components/cards/card-production-in-order.vue'
import CardProcessAbnormal from '@/views/mind/components/cards/card-process-abnormal.vue'
import CardPicking from '@/views/mind/components/cards/card-picking.vue'
import CardRelevancyPicking from '@/views/mind/components/cards/card-relevancy-picking.vue'
import CardEnterStock from '@/views/mind/components/cards/card-enter-stock.vue'
import CardMaterialTesting from '@/views/mind/components/cards/card-material-testing.vue'
import CardWorkOrderNo from '@/views/mind/components/cards/card-work-orderNo.vue'
import CardPurchase from '@/views/mind/components/cards/card-purchase.vue'
import CardBatch from '@/views/mind/components/cards/card-batch.vue'
import CardPickingAbnormal from '@/views/mind/components/cards/card-device-abnormal.vue'
// 数据演示
import byBarCode from '../demonstration-data/by_bar_code.json'
import byBatch from '../demonstration-data/by_batch.json'

export default {
  name: 'card-container',
  components: {
    LinkCircle
  },
  props: {
    parentId: {
      type: String,
      default: ''
    },
    position: {
      type: String,
      default: ''
    },
    isDataDemonstration: {
      type: Boolean,
      default: false
    },
    isShare: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    dataList() {
      return (
        this.$store.state.mind.nodeCards.filter((v) => v.parent[v.parent.length - 1] === this.parentId && v.position === this.position) ||
        []
      )
    },
    dictList() {
      return [
        { key: 'card-category', type: '二级分类' },
        {
          key: 'card-sale',
          type: '销售',
          codeType: '1'
        },
        {
          key: 'card-sale-list',
          type: '销售',
          codeType: '2'
        },
        {
          key: 'card-rectification',
          type: '整改'
        },
        {
          key: 'card-complain',
          type: '客诉',
          codeType: '1'
        },
        {
          key: 'card-complain-list',
          type: '客诉',
          codeType: '2'
        },
        {
          key: 'card-ship',
          type: '发货'
        },
        {
          key: 'card-out-stock',
          type: '出库',
          codeType: '1'
        },
        {
          key: 'card-out-stock-list',
          type: '出库',
          codeType: '2'
        },
        {
          key: 'card-plan',
          type: '计划'
        },
        {
          key: 'card-production',
          type: '生产'
        },
        {
          key: 'card-key-bind',
          type: '关键物料绑定'
        },
        {
          key: 'card-device-abnormal',
          type: '设备异常'
        },
        {
          key: 'card-production-in-order',
          type: '生产信息'
        },
        {
          key: 'card-process-abnormal',
          type: '工序异常'
        },
        {
          key: 'card-picking',
          type: '领料'
        },
        {
          key: 'card-relevancy-picking',
          type: '同批次关联领料单'
        },
        {
          key: 'card-enter-stock',
          type: '入库'
        },
        {
          key: 'card-material-testing',
          type: '来料检测'
        },
        {
          key: 'card-work-orderNo',
          type: '工单'
        },
        {
          key: 'card-purchase',
          type: '采购'
        },
        {
          key: 'card-batch',
          type: '批次'
        },
        {
          key: 'card-picking-abnormal',
          type: '领料异常'
        }
      ]
    },
    codeType() {
      return this.$store.state.mind.codeType
    }
  },
  data() {
    return {
      componentActive: {
        'card-category': CardCategory, // 二级分类
        'card-sale': CardSale, // 销售单
        'card-sale-list': CardSaleList, // 销售单列表
        'card-rectification': CardRectification, // 整改单
        'card-complain': CardComplain, // 客诉单
        'card-complain-list': CardComplainList, // 客诉单列表
        'card-ship': CardShip, // 发货单
        'card-out-stock': CardOutStock, // 出库单
        'card-out-stock-list': CardOutStockList, // 出库单列表
        'card-plan': CardPlan, // 计划
        'card-production': CardProduction, // 生产
        'card-key-bind': CardKeyBind, // 关键物料绑定
        'card-device-abnormal': CardDeviceAbnormal, // 设备异常
        'card-production-in-order': CardProductionInOrder, // 生产信息-按序
        'card-process-abnormal': CardProcessAbnormal, // 工序异常
        'card-picking': CardPicking, // 领料
        'card-relevancy-picking': CardRelevancyPicking, // 同批次关联领料单
        'card-enter-stock': CardEnterStock, // 入库
        'card-material-testing': CardMaterialTesting, // 来料检测
        'card-work-orderNo': CardWorkOrderNo, // 工单
        'card-purchase': CardPurchase, // 采购
        'card-batch': CardBatch, // 批次
        'card-picking-abnormal': CardPickingAbnormal // 领料异常
      }
    }
  },
  methods: {
    typeInit(type) {
      const obj = this.dictList.find((v) => v.type === type && (v.codeType === this.codeType || !v.codeType))
      if (obj) return obj
      return {}
    },
    dateInit(v, params) {
      if (
        [
          '销售日期',
          '出库时间',
          '操作日期',
          '报修时间',
          '返修时间',
          '复核时间',
          '评审时间',
          '入库时间',
          '检测时间',
          '完成时间',
          '采购时间',
          '报工时间',
          '操作时间'
        ].includes(params)
      ) {
        this.$set(v, params, moment(v[params]).format('YYYY-MM-DD HH:mm:ss'))
      }
    },
    paramsContrast(v, id, parent, position) {
      const { labelList, searchResults } = v
      const type = labelList.toString()
      // card参数
      this.$set(v, 'id', createId())
      this.$set(v, 'type', this.typeInit(type).key || '')
      this.$set(v, 'title', type)
      this.$set(v, 'active', false)
      this.$set(v, 'containerBg', '')
      this.$set(v, 'parent', [...parent, id])
      this.$set(v, 'position', position)
      // if (['card-sale-list', 'card-complain-list', 'card-out-stock-list'].includes(v.type)) {
      //   this.$set(v, 'existNextNode', false)
      // }
      // 展示参数
      searchResults.forEach((v) => {
        for (let results in v) {
          this.dateInit(v, results)
        }
      })
      if (type === '领料') {
        this.$set(
          v,
          '数量',
          v.searchResults
            .map((v) => v['数量'])
            .reduce((o, total) => {
              return o + total
            })
        )
        const { 领料单号, 工单, 操作人, 操作时间, 物料单位 } = v.searchResults[0]
        this.$set(v, '领料单号', 领料单号)
        this.$set(v, '工单', 工单)
        this.$set(v, '操作人', 操作人)
        this.$set(v, '操作时间', 操作时间)
        this.$set(v, '物料单位', 物料单位)
      } else {
        if (searchResults.length < 1) {
          for (let results in searchResults[0]) {
            this.$set(v, results, searchResults[0][results])
          }
        }
      }
    },
    linkCircleOpenInit(id, title) {
      this.$message.success(`【${title}】暂无条码追溯`)
      // this.msgSuccess(`【${title}】暂无条码追溯`)
      this.$refs[id][0].open = false
    },
    dataInit(id, parent, position, data) {
      let arr = [],
        dataInit = [],
        specialTypeArr = this.codeType === '1' ? ['领料', '生产信息'] : ['领料', '生产信息', '销售', '客诉', '出库']
      const obj = data.find((v) => specialTypeArr.includes(v.labelList.toString()))
      if (obj) {
        data.forEach((v) => {
          this.paramsContrast(v, id, parent, position)
        })
        arr = data
      } else {
        data.forEach((v) => {
          const { searchResults } = v
          searchResults.forEach((o) => {
            for (let i in v) {
              this.$set(o, i, v[i])
              this.$set(o, searchResults, [{ ...o }])
            }
          })
          dataInit = dataInit.concat(searchResults)
          dataInit.forEach((v) => {
            this.paramsContrast(v, id, parent, position)
          })
        })
        arr = dataInit
      }
      this.$store.commit('mind/addNodeCards', arr)
    },
    // 数据演示处理
    dataDemonstrationInit(dataItem, type, businessCode, mainField, id, parent, position, isBool) {
      let data = []
      if (this.codeType === '1') {
        if (['card-enter-stock', 'card-material-testing'].includes(type)) {
          data = byBarCode[`${type}-${dataItem[mainField]}`]
        } else {
          data = byBarCode[type]
        }
        this.handleLinkDataInit(data, isBool, businessCode, id, parent, position)
      } else {
        const includesFirst = ['card-enter-stock', 'card-material-testing'].includes(type),
          includesSecond = ['card-complain-list', 'card-out-stock-list'].includes(type)
        if (includesFirst || includesSecond) {
          if (typeof isBool !== 'undefined') {
            if (includesFirst) {
              data = byBatch[`${type}-${dataItem[mainField]}`]
            }
            if (includesSecond) {
              data = byBatch[`${type}-${dataItem.searchResults[0][mainField]}`]
            }
          } else {
            data = byBatch[`${type}-${dataItem[mainField]}`]
          }
        } else {
          data = byBatch[type]
        }
        if (typeof isBool !== 'undefined') {
          this.handleLinkDataInit(data, isBool, businessCode, id, parent, position)
        } else {
          this.handleClickDataInit(data, id, parent, position, businessCode)
        }
      }
    },
    // card操作
    handleLink({ dataItem, open }) {
      const { id, parent, childrens, mainField, nodeId, title, position, type } = dataItem
      const isBool = ['card-complain-list', 'card-out-stock-list'].includes(type)
      if (open) {
        if (childrens && childrens.length > 0) {
          this.dataInit(id, parent, position, childrens)
        } else {
          if (!mainField) {
            this.linkCircleOpenInit(id, title)
            return
          }
          const businessCode = dataItem['searchResults'][0][mainField]
          // 数据演示处理
          if (this.isDataDemonstration) {
            this.dataDemonstrationInit(dataItem, type, businessCode, mainField, id, parent, position, isBool)
            return
          }
          // 数据动态获取
          mindQueryNextNodes({ businessCode, nodeId }, this.isShare)
            .then((child) => {
              const { data } = child
              if (data && data.length > 0) {
                this.handleLinkDataInit(data, isBool, businessCode, id, parent, position)
              } else {
                this.linkCircleOpenInit(id, title)
                return
              }
            })
            .catch((err) => {
              this.$refs[id][0].open = false
            })
        }
      } else {
        if (id) {
          if (isBool) this.$refs[`component${id}`][0].active = ''
          this.$store.commit('mind/cleanSonNodeCards', id)
        }
      }
    },
    handleLinkDataInit(data, isBool, businessCode, id, parent, position) {
      if (isBool) this.$refs[`component${id}`][0].active = businessCode
      this.dataInit(id, parent, position, data)
    },
    // card列表点击
    handleClick({ item, dataItem }) {
      const { id, parent, mainField, nodeId, position, title, type } = dataItem
      if (!mainField) {
        this.$message.success(`【${title}】暂无条码追溯`)
        return
      }
      const businessCode = item[mainField]
      // 数据演示处理
      if (this.isDataDemonstration) {
        this.dataDemonstrationInit(item, type, businessCode, mainField, id, parent, position)
        return
      }
      // 动态数据获取
      mindQueryNextNodes({ businessCode, nodeId }, this.isShare)
        .then((child) => {
          const { data } = child
          if (data && data.length > 0) {
            this.handleClickDataInit(data, id, parent, position, businessCode)
          } else {
            this.$refs[id][0].open = false
            this.msgSuccess(`【${title}】【${businessCode}】暂无条码追溯`)
          }
        })
        .catch((err) => {
          this.$refs[id][0].open = false
        })
    },
    handleClickDataInit(data, id, parent, position, businessCode) {
      let arr = [],
        dataInit = []
      this.$refs[`component${id}`][0].active = businessCode
      this.$refs[id][0].open = true
      // this.$set(dataItem, 'existNextNode', true)
      // 数据初始化
      data.forEach((v) => {
        const { searchResults } = v
        searchResults.forEach((o) => {
          for (let i in v) {
            this.$set(o, i, v[i])
            this.$set(o, searchResults, [{ ...o }])
          }
        })
        dataInit = dataInit.concat(searchResults)
        dataInit.forEach((v) => {
          this.paramsContrast(v, id, parent, position)
        })
      })
      let nodeCards = this.$store.state.mind.nodeCards
      // 去重
      nodeCards.forEach((v, index) => {
        if (v.nodeId === data[0].nodeId) {
          nodeCards.splice(index, 1)
        }
      })
      arr = dataInit
      this.$store.commit('mind/addNodeCards', arr)
    }
  }
}
</script>
<style lang="scss">
.type-wrapper + .type-wrapper {
  margin-top: 52px;
}
</style>
